import validator from 'el-form-validator';

export default {
    data() {
        return {
            _timeOut: undefined,
            errors: {},
            data: this.value,
            rules: {}
        };
    },
    props: {
        value: {
            type: Object,
            default: () => {
                return {};
            }
        },
        errorMessages: Object
    },
    watch: {
        value(n) {
            this.data = n;
        },
        data: {
            handler(n) {
                this._clearTimeOut();
                this._timeOut = setTimeout(() => {
                    this._validatorData();
                }, 100);
                this.$emit('input', n);
            },
            deep: true
        },
        errorMessages (errors) {
            this.errors = errors;
        }
    },
    methods: {
        _validatorData() {
            let valid = validator.make(this.data, this.rules);
            if (valid.fails()) {
                this.errors = valid.getErrors();
            } else {
                this.errors = [];
            }
        },
        onSubmit() {
            this._validatorData();
            if (this.errors.length === 0) return this.$emit('submit', this.data);
        },
        _clearTimeOut() {
            if (this._timeOut !== undefined) clearTimeout(this._timeOut);
            this._timeOut = undefined;
        }
    }
};
